package com.youlu.campus.web.order.service;

import com.youlu.campus.base.order.enums.GoodsStatusEnum;
import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.order.entity.vo.GoodsVO;
import com.youlu.campus.web.order.entity.GoodsPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zgz
 * @date 2020/8/3 18:20
 */
@Service
@Slf4j
public class GoodsService extends BaseService {

    public GoodsVO getGoodsByCode(String goodsCode) {
        log.info("getGoodsByCode goodsCode {}", goodsCode);
        Query query = new Query();
        query.addCriteria(Criteria.where("goodsCode").is(goodsCode));
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("status").is(GoodsStatusEnum.ON.getCode()));
        GoodsPO goodsPO = mongoTemplate.findOne(query, GoodsPO.class);
        if (goodsPO == null) {
            return null;
        }
        GoodsVO goodsVO = new GoodsVO();
        BeanUtils.copyProperties(goodsPO, goodsVO);
        goodsVO.setGoodsId(goodsPO.getId());
        return goodsVO;
    }

    public void handleSaleCount(String goodsId) {
        Query goodsQuery = new Query();
        goodsQuery.addCriteria(Criteria.where("id").is(goodsId));
        Update update = new Update();
        update.inc("saleNum");
        update.set("updatedTime", new Date());
        mongoTemplate.updateFirst(goodsQuery, update, GoodsPO.class);
    }
}
